import React, { Component } from 'react'
import {
  StyleSheet,
  View,
  ScrollView,
  Dimensions,
  Text,
  TouchableOpacity,
  Animated
} from 'react-native'
import {Icon} from '../components/common/icon'
import NavigationBar from '../components/common/NavigationBar'
import SearchInput from '../components/common/SearchInput'
import SwipeListItem from '../components/common/SwipeListItem'
import Drawer from 'react-native-drawer'
import ChooseScenceList from './ChooseScenceList'
import {connect} from 'react-redux'
import EntityLabels from '../constants/entities'
import assign from 'lodash/assign'
import values from 'lodash/values'

const { width, height } = Dimensions.get('window')
const floorMap = {
  '-2': '负二楼',
  '-1': '负一楼',
  '1': '一楼',
  '2': '二楼',
  '3': '三楼',
  '4': '四楼',
  '5': '五楼',
  '6': '六楼',
  '7': '七楼',
  '8': '八楼',
  '9': '九楼',
  '10': '十楼',
  '11': '十一楼',
  '12': '十二楼',
  '13': '十三楼',
  '14': '十四楼',
  '15': '十五楼',
}

class ScenceList extends Component {
  constructor(props) {
    super(props)

    this._rightIconEvent = this._rightIconEvent.bind(this)
    this.filterScene = this.filterScene.bind(this)
    this.state = {
      rightText: '筛选',
      drawerState: false,
      fadeAnim: new Animated.Value(0),
      list: [],
      floorList: []
    }
  }
  convertPropsToStates(props) {
		const { scenesEntities, roomEntities } = props
    const scenceList = scenesEntities && values(scenesEntities)
    const roomList = roomEntities && values(roomEntities)
    console.warn(JSON.stringify(scenceList))
    console.warn(JSON.stringify(roomList))
    this.setState({
      scenceList,
      roomList
    }, () => {
      this.initScenceData()
      this.initFloorData()
    })
	}

	componentWillReceiveProps(nextProps) {
		this.convertPropsToStates((nextProps));
	}
	componentWillMount() {
		this.convertPropsToStates(this.props);
  }
  initScenceData() {

    let _roomList = JSON.parse(JSON.stringify(this.state.roomList || []))
    let _scenceList = JSON.parse(JSON.stringify(this.state.scenceList || []))
    let _wholeHouseSceneList = []
    if(_roomList.length > 0){
      for(let i = 0; i < _roomList.length; i++){
        _roomList[i]['data'] = []
        _roomList[i].name = _roomList[i].floor ? `${floorMap[_roomList[i].floor]}·${_roomList[i].name}` : `一楼·${_roomList[i].name}`
        for(let j = 0; j < _scenceList.length; j++){
          if(_scenceList[j].roomId){
            if(_scenceList[j].roomId === _roomList[i].id){
              _roomList[i]['data'].push(_scenceList[j])
            }
          }else{
            _wholeHouseSceneList.push(_scenceList[j])
          }
        }
      }

      if(_wholeHouseSceneList.length > 0){
        _roomList.unshift({
          name: '全屋场景',
          data: _wholeHouseSceneList
        })
      }
    }
    console.warn('_roomList'+JSON.stringify(_roomList))
    this.setState({
      list: _roomList
    })
  }
  initFloorData() {
    let _roomList = JSON.parse(JSON.stringify(this.state.roomList || []))
    let _floorList = []
    if(_roomList.length){
      _floorList = Array.from(new Set(_roomList.map(item => {
        return item.floor ? item.floor : 1
      })))

      console.warn(JSON.stringify(_floorList))
    }
    this.setState({
      floorList: _floorList.map(item => {
        return {
          key: item,
          value: floorMap[item]
        }
      })
    })
  }
  render() {
    const rightElement = <Text style={styles.rightText} onPress={this._rightIconEvent}>{this.state.rightText}</Text>
    const fadeView = <Animated.View style={[{opacity: this.state.fadeAnim}, styles.opacityView]}></Animated.View>
    return (
      <View style = {styles.container}>
        <NavigationBar
          title={'场景列表'}
          statusBar={{backgroundColor: '#ffffff', barStyle: 'dark-content'}}
          style={{backgroundColor: '#ffffff'}}
          rightButton={rightElement}
          navigator={this.props.navigator}
        />
        <Drawer
          type='overlay'
          open={this.state.drawerState}
          content={<ChooseScenceList floorList={this.state.floorList} filterScene={this.filterScene} />}
          tapToClose={false}
          side={'right'}
          panOpenMask={0}
          openDrawerOffset={0.3} // 20% gap on the right side of drawer
          panCloseMask={0}
          closedDrawerOffset={0}
          style={styles.content}>
          <SearchInput placeholder={'搜索场景、模式名称'}></SearchInput>
          <ScrollView style={styles.content}>
            <SwipeListItem data={this.state.list} />
          </ScrollView>
        </Drawer>
        {this.state.drawerState && fadeView}
      </View>
    )
  }
  _rightIconEvent() {
    let drawerState = !this.state.drawerState
    let rightText = drawerState ? '取消' : '筛选'
    let fadeAnimValue = drawerState ? 0.5 : 0
    this.animatedEvent(fadeAnimValue)
    this.setState(() => ({
      rightText: rightText,
      drawerState: drawerState,
    }))
  }
  animatedEvent(fadeAnimValue) {
    console.warn(fadeAnimValue)
    Animated.timing(                  // 随时间变化而执行动画
      this.state.fadeAnim,            // 动画中的变量值
      {
        toValue: fadeAnimValue,       // 透明度最终变为1，即完全不透明
        duration: 300,              // 让动画持续一段时间
      }
    ).start();
  }
  filterScene(data) {
    this._rightIconEvent()
    console.warn('currentfloor' + data)
  }
}

function mappingStateToProps(state, ownProps) {
	const entities= state['entities'];
  const scenesEntities = entities[EntityLabels.scenes];
  const roomEntities = entities[EntityLabels.room];

	return {
    scenesEntities,
    roomEntities
	};
}

export default connect(mappingStateToProps)(ScenceList);

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#F4F4F4',
    flex: 1,
  },
  rightText: {
    fontSize: 13,
    color: '#00A5AD',
  },
  content: {
    flex: 1,
    backgroundColor: '#ffffff'
  },
  opacityView: {
    width: width * 0.3,
    height: height - 48,
    position: 'absolute',
    top: 48,
    left: 0,
    backgroundColor: '#000000'
  }
})
